<!--
 * @Author: 冯尚新 fengshangxin@yunjinhz.com
 * @Date: 2023-05-23 10:51:57
 * @LastEditors: 冯尚新 fengshangxin@yunjinhz.com
 * @LastEditTime: 2023-05-30 20:54:12
 * @FilePath: \zmglpt-ui-mobile-v1.1\dev\pages\internal\fieldAudit\index.vue
 * @Description: 实地核查
-->

<template>
	<view>
		<!-- #ifdef H5-ONLY -->
		<theme-navbar :is-white="false" :title="navTitle" :custom-back="goBack" style="z-index: 99999">
			<view class="nav-right-icon">
				<span @tap="showSearch=true">
					<u-icon name="search" color="#FFF" size="38"></u-icon>
				</span>
				<span @tap="handleScan" style="margin-left: 8px;">
					<u-icon name="scan" color="#FFF" size="38"></u-icon>
				</span>
			</view>
		</theme-navbar>
		<!-- #endif -->
		<!-- #ifdef H5-DINGDING -->
		<fab-button :content="fContent" @fabtrigger="fabtrigger" />
		<!-- #endif -->
    <!-- #ifdef H5-WECHAT || H5-EMP -->
    <fab-button :content="fContent" @fabtrigger="fabtrigger" />
    <!-- #endif -->
		<!-- 条件筛选 -->
		<u-popup mode="right" width="80%" v-model="showSearch">
			<u-card :show-foot="false" title="查询条件" margin="0">
				<view slot="body">
					<view style="margin-bottom:25px;">
						<u-input placeholder="客户名称、许可证号、负责人" :border="true" v-model="formData.search" />
					</view>
					<view class="left-text">
						任务类型
					</view>
					<view style="margin-bottom:34px;">
						<z-dict-radio :dictType="$u.dic.DIC_KEYS.I_FIELD_CHECK_SOURCE" v-model="formData.taskSource"></z-dict-radio>
					</view>
					<view class="left-text">
						任务时间
					</view>
					<view style="margin-bottom:34px;">
						<u-form-item>
							<span class="date-width"><z-date placeholder="开始时间" v-model="formData.requestTimeBegin" /></span>
							<span class="between">至</span>
							<span class="date-width"><z-date placeholder="结束时间" v-model="formData.requestTimeEnd" /></span>
						</u-form-item>
					</view>
					<view class="left-text">
						核查状态
					</view>
					<view style="margin-bottom:34px;">
						<z-dict-radio :dictType="$u.dic.DIC_KEYS.I_FIELD_CHECK_STATE" v-model="formData.status"></z-dict-radio>
					</view>
					<view class="left-text">
						流程逾期
					</view>
					<view style="margin-bottom:34px;">
						<u-radio-group v-model="formData.overdue" @change="radioChange">
							<u-radio name="0" shape="square">
								未逾期
							</u-radio>
							<u-radio name="1" shape="square">
								已逾期
							</u-radio>
						</u-radio-group>
					</view>
				</view>
			</u-card>
			<u-row justify="space-around">
				<u-col span="6" text-align="center">
					<u-button @tap="formData={}" style="border: 2px solid #0079F2;">
						重置
					</u-button>
				</u-col>
				<u-col span="6" text-align="center">
					<u-button type="primary" @tap="handleSearch">
						搜索
					</u-button>
				</u-col>
			</u-row>
		</u-popup>
		<view>
			<div :style="{height: screenHeight/3 + 'px'}" id="retailers-map-container"></div>
		</view>
		<view style="margin-top: -25px; z-index: 10; position: relative;">
			<me-table :i="0" :index="0" :top="0" :load-data="loadData" :init-load="false" ref="mescrollItem0">
				<template #default="d">
					<field-check-item :key="d.data.licNo" @click-body="handlerTapCheckItem(d.data)" :data="d.data" :selected-list="selectedChecks" @click-head="handleClickHead"></field-check-item>
				</template>
			</me-table>
		</view>
	</view>
</template>
<script>
	import meTable from '@/components/me-table.vue';
	import MescrollMoreMixin from "@/components/mescroll-uni/mixins/mescroll-more.js";
	import {
		AMapMixin,
	} from '@/common/AMapMixin.js';
	import {
		ZDate,
		ZDictRadio,
	} from '@/components';
	import { SET_MAP_LAT_LON } from '@/config/setting.config.js';
	import fieldAuditService from "@/service/internal/fieldAudit.service.js";
	import FieldCheckItem from './components/field-check-item.vue';
	import fabButton from '@/components/uni-fab.vue';
	const screenHeight = uni.getSystemInfoSync().screenHeight;
	export default {
		components: {
			meTable,
			ZDate,
			ZDictRadio,
			FieldCheckItem,
			fabButton
		},
		mixins: [MescrollMoreMixin, AMapMixin, ],
		data() {
			return {
				showSearch: false,
				checkShow: false,
				show: false, // 导航栏右侧按钮显示标识符
				formData: {},
				listData: [], // 核查客户数据
				checkData: [],
				selectedChecks: [], // 当前选中的
				screenHeight: screenHeight,
				amap: null, // 地图对象
				retailerIcon: null, // 零售户icon
				retailerSelectIcon: null, // 零售户选中icon
				overlayGroups: [], // 覆盖物信息
				markers: [], // 标记物
				fContent: [{
						iconPath: require("@/static/sou.png"),
						selectedIconPath: require("@/static/sou.png"),
						text: '筛选',
						active: false,
					},
					{
						iconPath: require("@/static/scode.png"),
						selectedIconPath: require("@/static/scode.png"),
						text: '扫一扫',
						active: false,
					},
				],
        curCords: []
			}
		},
		watch: {
			selectedChecks: {
				deep: true,
				handler(v) {
					console.log("选中了", v);
				},
			},
		},
		// 页面加载成功后也要设置一次，用于处理本页面刷新后失效问题
		mounted() {
			// this.setRightBtns();
		},
		methods: {
			loadData(page) {
				return new Promise(resolve => {
					fieldAuditService.listFieldCheck(page.num, page.size, this.formData).then((res) => {
						if (res.success) {
							resolve(res);
							this.listData = [...res.data, ...this.listData, ];
							this.totalCount = res.count;
							this.addOverlay();
						} else {
							this.$u.toast(res.msg);
						}
					}).catch((error) => {
						this.$u.toast(error);
					});
				});
			},
			// 初始化地图
			initAmap() {
        let self = this;
        // #ifdef H5-DINGDING || H5-WECHAT
        this.getCurrentLocation().then(
            (res) => {
              self.curPos = [res.lng, res.lat];
              self.setMapInstance([res.lng, res.lat]);
            },
            (err) => {
            }
        );
        // #endif
				// #ifdef H5-ONLY
				self.curPos = SET_MAP_LAT_LON;
				self.setMapInstance(SET_MAP_LAT_LON);
				// #endif
			},

      setMapInstance(cords) {
        this.retailerIcon = new AMap.Icon({
          size: new AMap.Size(24, 24), // 图标尺寸
          image: require("@/static/check/marker.png"), // Icon的图像
          imageSize: new AMap.Size(24, 24), //,
        });
        this.retailerSelectIcon = new AMap.Icon({
          size: new AMap.Size(24, 24), // 图标尺寸
          image: require("@/static/check/marker_selected.png"), // Icon的图像
          imageSize: new AMap.Size(24, 24), //,
        });
        if (!this.hasInited) return;
        this.$modal.showLoading('地图加载中...');
        this.curCords = new AMap.LngLat(cords[0], cords[1]);
        this.amap = new AMap.Map('retailers-map-container', {
          // center: new AMap.LngLat(121.525909,29.877595),
          zoom: 12,
          resizeEnable: true,
          scrollWheel: true,
          zoomEnable: true,
          mapStyle: 'amap://styles/fresh',
          center: this.curCords
        });
        this.$modal.hideLoading();
        this.loadPlugin([
          // 'AMap.ToolBar',
          // 'AMap.Scale',
          'AMap.OverView',
          'AMap.Geolocation',
        ], () => {
          // this.amap.addControl(new AMap.ToolBar());
          // 在图面添加比例尺控件，展示地图在当前层级和纬度下的比例尺
          // this.amap.addControl(new AMap.Scale());
        });
      },
			// 添加检查户标记
			addOverlay() {
				this.markers = [];
				this.listData.forEach((mg, idx) => {
					// let isExist = this.listData.filter(sc => sc.licNo == mg.licNo).length > 0;
					if (!mg.longitudeIn || !mg.latitudeIn) {
						return;
					}
					let isExist = false;
					let markerConfig = {
						title: mg.customerName,
						icon: isExist ? this.retailerSelectIcon : this.retailerIcon,
						position: [mg.longitudeIn, mg.latitudeIn ],
						offset: new AMap.Pixel(-8, 5),
						label: {},
					};
					if (idx < 30) {
						markerConfig.label = {
							content: mg.customerName,
							offset: new AMap.Pixel(26, 1),
						}
					}
					let marker = new AMap.Marker(markerConfig);
					marker.retailer = mg;
					let self = this;
					marker.on("click", (m) => {
						let sChecks = self.selectedChecks.filter(sc => sc.licNo == m.target.retailer.licNo);
						if (sChecks.length > 0) {
							m.target.setIcon(self.retailerIcon);
							self.selectedChecks = self.selectedChecks.filter(sc => sc.licNo != m.target.retailer.licNo);
						} else {
							m.target.setIcon(self.retailerSelectIcon);
							self.selectedChecks.push(m.target.retailer);
						}
					});
					this.markers.push(marker);
				});
				this.amap.clearMap();
				this.overlayGroups = new AMap.OverlayGroup(this.markers);
				this.amap.add(this.overlayGroups);
			},
			handleAdd() {
				// this.$u.route("pages/internal/fieldAudit/indexAdd");
				this.$u.route("/pages/internal/retailerList");
			},
			// 根据页面返回的参数处理相应逻辑, 方法名updateBackState固定
			updateBackState(param) {
				// 选中的卷烟
				let selectRetailers = param[this.$rp.check.CHECK_CLIENT];
				this.$modal.showLoading('添加中...');
				fieldAuditService.addToCheck(selectRetailers.map(s => s.licNo).join(",")).then((res) => {
					this.$modal.hideLoading();
					if (res.success) {
						this.$refs.mescrollItem0.refresh();
					} else {
						this.$u.toast(res.msg);
					}
				});
			},
			radioChange(e) {
				console.log("this.formData.taskType:" + this.formData.taskType);
			},
			checkboxChange(e) {
				if (e.value == true) {
					this.listData.forEach(d => {
						if (d.licNo == e.name) {
							this.checkData.push(d);
						}
					});
				} else {
					// 取消勾选，删除元素
					for (let i = 0; i < this.checkData.length; i++) {
						if (this.checkData[i].licNo == e.name) {
							this.checkData.splice(i, 1);
						}
					}
				}
				console.log(this.checkData);
			},
			// 筛选
			handleSearch() {
				this.showSearch = false;
				this.$refs.mescrollItem0.refresh();
			},
			setRightBtns() {
				// 设置右侧标题
				// #ifdef H5-DINGDING
				let menuItemStr = '[{"id": "1", "text": "筛选"},{"id": "4", "text": "扫一扫"}]';
				this.$deviceApi.setMenu(JSON.parse(menuItemStr), res => {
					if (res.id == 1) { // 筛选
						this.showSearch = true;
					} else { // 扫一扫
						this.handleScan();
					}
				});
				// #endif
			},
			// 扫一扫
			handleScan() {
				this.$deviceApi.scan().then(res => {
					let licNo = res.replace(/ +/g, "").replace(/[\r\n]/g, "");
					try {
						let start = licNo.indexOf('许可证号') + 5;
						let num = licNo.indexOf('发证机关') - start;
						licNo = licNo.substr(start, num);
					} catch (e) {
						console.log(e);
					}
					if (!this.$u.test.digits(licNo)) {
						this.$u.toast('无法识别许可证号');
						return;
					}
					// 识别成功
					if (licNo != this.checkInfo.licNo) {
						this.$u.toast("您扫描的信息与当前零售户不一致");
						return;
					}
					this.formData.search = licNo;
					this.$refs.mescrollItem0.refresh();
				});
			},
			// 点击列表项
			handlerTapCheckItem(item) {
				console.log("查看检查任务", item);
				this.setRouteParam(item);
				this.$u.route("pages/internal/fieldAudit/fieldAuditDetail");
			},
			// 点击卡头
			handleClickHead(item) {
				console.log("点击卡头", item);
				let sMarker = this.markers.filter(m => m.retailer.licNo === item.licNo)[0];
				let cMarker = this.selectedChecks.filter(m => m.licNo === item.licNo);
				if (cMarker.length > 0) {
					sMarker.setIcon(this.retailerIcon);
					this.selectedChecks = this.selectedChecks.filter(sc => sc.licNo != sMarker.retailer.licNo);
				} else {
					sMarker.setIcon(this.retailerSelectIcon);
					this.selectedChecks.push(sMarker.retailer);
				}
				this.amap.clearMap();
				this.overlayGroups = new AMap.OverlayGroup(this.markers);
				this.amap.add(this.overlayGroups);
				this.amap.setCenter([sMarker.retailer.longitudeIn, sMarker.retailer.latitudeIn ]);
			},
			fabtrigger(act) {
				if (act.index === 0) {
					this.showSearch = true;
				} else if (act.index === 1) {
					this.handleScan();
				}
			},
		},
	}
</script>
<style lang="scss" scoped>
	.between {
		width: 40px;
		text-align: center;
	}
</style>
